import scrapy
from ..items import QkMovie099Item


class MvSpider(scrapy.Spider):
    name = "mv"
    allowed_domains = ["www.dy2018.com"]
    start_urls = ["https://www.dy2018.com/html/gndy/dyzz/index.html"]

    def parse(self, response):
        # 要第一页的名字和第二页的图片
        # name = //div[@class="co_content8"]//table//td[2]//a/@title
        # src_base_url = //div[@class="co_content8"]//table//td[2]//a/@href
        a_list = response.xpath('//div[@class="co_content8"]//table//td[2]//a[@class="ulink"]')

        for a in a_list:
            # 获取第一页的name 和要点击的链接
            name = a.xpath('./text()').extract_first()
            href = a.xpath('./@href').extract_first()

            # 第二页的地址是
            url = 'https://www.dy2018.com' + href

            # 对第二页的链接发起访问
            yield scrapy.Request(url=url, callback=self.parse_second, meta={'name': name})

    def parse_second(self, response):
        # 如果拿不到数据 检查xpath语法
        src = response.xpath('//div[@id="Zoom"]/img[1]/@src').extract_first()
        # 接收到请求的meta参数的值
        name = response.meta['name']

        movie = QkMovie099Item(src=src, name=name)

        yield movie

